package model

import (
	log "github.com/sirupsen/logrus"
	"gorm.io/gorm"
	"myginblog/utils"
	"myginblog/utils/errmsg"
)

type User struct {
	gorm.Model
	Username string `gorm:"type:varchar(20);not null " json:"username"`
	Password string `gorm:"type:varchar(20);not null " json:"password"`
	Role     int    `gorm:"type:int" json:"role"`
}

func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
	u.Password = utils.ScryptPd(u.Password)
	return nil
}

// CheckUser 查询用户是否存在
func CheckUser(name string) int {
	var users User
	err = db.Where("username = ?", name).First(&users).Error
	if users.ID > 0 {
		//	1001
		return errmsg.ErrorUsernameUsed
	}
	return errmsg.SUCCESS
}

// CreatUser 新增用户
func CreatUser(data *User) int {
	//data.Password = utils.ScryptPd(data.Password)
	err = db.Create(&data).Error
	if err != nil {
		log.Error(err)
		//	500
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

// GetUsers 获取用户列表
func GetUsers(pageSize int, pageNum int) []User {
	var users []User
	if pageNum == 0 {
		pageNum = 1
	}
	err = db.Limit(pageSize).Offset((pageNum - 1) * pageSize).Find(&users).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		log.Error(err)
		return nil
	}
	return users
}

// EditUser 编辑用户信息
func EditUser(id int, data *User) int {
	var user User
	var userMap = make(map[string]interface{})
	userMap["username"] = data.Username
	userMap["role"] = data.Role
	err = db.Model(&user).Where("id = ? ", id).Updates(userMap).Error
	if err != nil {
		log.Error(err)
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

// DeleteUser 删除用户
func DeleteUser(id int) int {
	var user User
	err = db.Where("id = ? ", id).Delete(&user).Error
	if err != nil {
		log.Error(err)
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}
